package org.xxpay.pay.channel.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayResponse;
import com.alipay.api.request.AlipayMarketingCampaignCashCreateRequest;
import com.alipay.api.request.AlipayMarketingCampaignCashDetailQueryRequest;
import com.alipay.api.request.AlipayMarketingCampaignCashStatusModifyRequest;
import com.alipay.api.request.AlipayMarketingCampaignCashTriggerRequest;
import com.alipay.api.response.AlipayMarketingCampaignCashCreateResponse;
import com.alipay.api.response.AlipayMarketingCampaignCashDetailQueryResponse;
import com.alipay.api.response.AlipayMarketingCampaignCashStatusModifyResponse;
import com.alipay.api.response.AlipayMarketingCampaignCashTriggerResponse;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.AlipayCash;
import org.xxpay.core.entity.AlipayCashDetail;

import java.net.URLDecoder;

/** 支付宝现金活动 **/
@Service
public class AlipayCampaignCashService {

    private static final MyLog _log = MyLog.getLog(AlipayCampaignCashService.class);

    /** 创建红包 **/
    public boolean create(String alipayPayParams, AlipayCash cash) {

        try {
            AlipayConfig alipayConfig = new AlipayConfig(alipayPayParams);

            JSONObject reqData = new JSONObject();
            reqData.put("coupon_name", cash.getCouponName()); //红包名称
            reqData.put("prize_type", cash.getPrizeType());  //发放形式： random=随机(平均金额的0.5-1.5倍), fixed=固定金额
            reqData.put("total_money", AmountUtil.convertCent2DollarShort(cash.getTotalMoney() + "")); //活动发放的现金总金额 单位：元, 最小金额为1.00元, 最大金额为10000000.00元, 每个红包最大金额200, 最小金额0.2元。 (沙箱环境 0.1元也可以。。。。。 随机的话0.05也可以....)
            reqData.put("total_num", cash.getTotalNum());   //红包个数， 1-10000000，
            reqData.put("prize_msg", cash.getPrizeMsg());   //描述信息, 提现在账单描述, 红包描述中
            reqData.put("start_time", DateUtil.date2Str(cash.getStartTime()));  //活动开始时间：格式为 yyyy-MM-dd HH:mm:ss
            reqData.put("end_time", DateUtil.date2Str(cash.getEndTime()));    //活动结束时间, 活动有效时间最长为6个月
            reqData.put("merchant_link", "");   //商户打款后的跳转链接, 非必填
            reqData.put("send_freqency", cash.getSendFreqency());   //用户在当前活动参与次数、频率限制。 默认为L1

            AlipayMarketingCampaignCashCreateRequest req = new AlipayMarketingCampaignCashCreateRequest();
            req.setBizContent(reqData.toJSONString());
            AlipayMarketingCampaignCashCreateResponse resp = AlipayConfig.alipayExecute(alipayConfig, req);
            if(resp.isSuccess()){ //请求成功

                cash.setAlipayCrowdNo(resp.getCrowdNo()); //红包编号
                cash.setAlipayOriginCrowdNo(resp.getOriginCrowdNo()); //红包原始编号
                cash.setAlipayPayUrl(URLDecoder.decode(resp.getPayUrl())); //支付地址
                cash.setAlipayStatus("CREATED"); //创建成功状态为：已创建未打款
                return true;

            }else{
                cash.setAlipayErrorMsg(getErrMsg(resp));
                return false;
            }
        } catch (AlipayApiException e) {
            _log.error("AlipayApiException", e);
            cash.setAlipayErrorMsg("AlipayClient execute error");
            return false;
        }catch (Exception e){
            _log.error("Exception", e);
            cash.setAlipayErrorMsg("支付系统异常" + e.getMessage());
            return false;
        }
    }

    /** 查询红包 **/
    public AlipayCash query(String alipayParams, String alipayCrowdNo) {

        try {

            JSONObject reqData = new JSONObject();
            reqData.put("crowd_no", alipayCrowdNo); //红包活动号 例：POYb84lfiKVdIfERAYsqPL_KQRIpfQbl47xfRmmPBlDMnSZ96O-zxUfKlHp5cxmx

            AlipayConfig alipayConfig = new AlipayConfig(alipayParams);

            AlipayMarketingCampaignCashDetailQueryRequest req = new AlipayMarketingCampaignCashDetailQueryRequest();
            req.setBizContent(reqData.toJSONString());
            AlipayMarketingCampaignCashDetailQueryResponse resp = AlipayConfig.alipayExecute(alipayConfig, req);

            if(resp.isSuccess()){

                JSONObject queryRespJSON = JSONObject.parseObject(resp.getBody());

                AlipayCash result = new AlipayCash();

                result.setAlipayCrowdNo(resp.getCrowdNo()); //活动号
                result.setCouponName(resp.getCouponName()); //红包名称
                result.setPrizeMsg(resp.getPrizeMsg());   //活动文案
                result.setPrizeType(resp.getPrizeType());  //发放形式
                result.setStartTime(resp.getStartTime());  //开始时间
                result.setEndTime(resp.getEndTime());    //结束时间
                result.setTotalMoney(Long.parseLong(AmountUtil.convertDollar2Cent(resp.getTotalAmount())));    //活动总金额
                result.setAlipaySendAmount(Long.parseLong(AmountUtil.convertDollar2Cent(resp.getSendAmount()))); //活动已发放金额
                result.setTotalNum(queryRespJSON.getJSONObject("alipay_marketing_campaign_cash_detail_query_response").getInteger("total_count")); //红包总个数
                result.setAlipayOriginCrowdNo(resp.getOriginCrowdNo()); //原始活动号,用于排查问题
                result.setAlipayStatus(resp.getCampStatus()); //活动状态
                return result;
            }else{

                _log.error("查询失败:{}", getErrMsg(resp));
            }
        } catch (AlipayApiException e) {
            _log.error("AlipayApiException", e);
        }catch (Exception e) {
            _log.error("Exception", e);
        }
        return null;
    }

    /** 更改红包状态 **/
    public JSONObject modifyStatus(String alipayPayParams, String crowdNo, String modifyStatus){

        JSONObject result = new JSONObject();

        try {
            AlipayConfig alipayConfig = new AlipayConfig(alipayPayParams);
            AlipayMarketingCampaignCashStatusModifyRequest request = new AlipayMarketingCampaignCashStatusModifyRequest();
            JSONObject reqObject = new JSONObject();
            reqObject.put("crowd_no", crowdNo);
            reqObject.put("camp_status", modifyStatus);
            request.setBizContent(reqObject.toString());
            AlipayMarketingCampaignCashStatusModifyResponse resp = AlipayConfig.alipayExecute(alipayConfig, request);
            if(resp.isSuccess()){
                result.put("isSuccess", true);
                return result;
            }else{
                _log.error("更新状态失败{}", getErrMsg(resp));
                result.put("isSuccess", false);
                result.put("errMsg", getErrMsg(resp)); //错误信息
                return result;
            }
        } catch (AlipayApiException e) {
            _log.error("AlipayApiException", e);
            result.put("isSuccess", false);
            result.put("errMsg", "调起接口失败"); //错误信息
            return result;

        }
        catch (Exception e) {
            _log.error("Exception", e);
            result.put("isSuccess", false);
            result.put("errMsg", "支付系统异常"); //错误信息
            return result;
        }
    }

    /** 触发领取红包 **/
    public JSONObject trigger(String alipayPayParams, String crowdNo, AlipayCashDetail detail) {

        JSONObject result = new JSONObject();

        try {
            AlipayConfig alipayConfig = new AlipayConfig(alipayPayParams);

            JSONObject reqData = new JSONObject();
            reqData.put("crowd_no", crowdNo); //红包活动号 例：POYb84lfiKVdIfERAYsqPL_KQRIpfQbl47xfRmmPBlDMnSZ96O-zxUfKlHp5cxmx
            reqData.put("user_id", ""); // userId 与 loginId 二选一， 如都存在值，已userId为准
            reqData.put("login_id", detail.getAlipayLoginId()); // 邮箱或手机号
            reqData.put("order_price", detail.getPlanAmount()); // 金额 单位分， 如传入则忽略prize_type指定的算法规则，按照order_price进行下发金额
            reqData.put("out_biz_no", detail.getId()); //外部订单号

            AlipayMarketingCampaignCashTriggerRequest req = new AlipayMarketingCampaignCashTriggerRequest();
            req.setBizContent(reqData.toJSONString());
            AlipayMarketingCampaignCashTriggerResponse resp = AlipayConfig.alipayExecute(alipayConfig, req);


            if(resp.isSuccess()){
                boolean triggerResult = "true".equalsIgnoreCase(resp.getTriggerResult());
                boolean repeatTriggerFlag = "true".equalsIgnoreCase(resp.getRepeatTriggerFlag());

                if(triggerResult && !repeatTriggerFlag){ ///领取成功 & 非重复领取
                    Long prizeAmount = Long.parseLong(AmountUtil.convertDollar2Cent(resp.getPrizeAmount()));
                    result.put("isSuccess", true); //用户领取成功
                    result.put("prizeAmount", prizeAmount); //领取金额
                }else{
                    result.put("isSuccess", false); //分账失败
                    result.put("errMsg", "用户未中奖或重复领取[triggerResult = "+triggerResult+" | repeatTriggerFlag="+repeatTriggerFlag+" ]|errMsg=" +resp.getErrorMsg()); //错误信息
                }

                return result;
            }else{

                result.put("isSuccess", false); //分账失败
                result.put("errMsg",getErrMsg(resp));
                return result;
            }

        } catch (AlipayApiException e) {
            _log.error("AlipayApiException", e);
            result.put("isSuccess", false); //分账失败
            result.put("errMsg", "调起接口失败"); //错误信息
            return result;

        }
        catch (Exception e) {
            _log.error("Exception", e);
            result.put("isSuccess", false); //分账失败
            result.put("errMsg", "支付系统异常"); //错误信息
            return result;
        }
    }


    private String getErrMsg(AlipayResponse resp){
        return "code="+resp.getCode()+"|msg="+resp.getMsg()+"|subCode="+resp.getSubCode()+"|subMsg=" + resp.getSubMsg();
    }

}
